package com.xzp.gkrpc.common.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.LinkedList;

public class ReflectionUtils {
    /**
     * 根据clazz创建对象实例
     * @param clazz 待创建对象的类
     * @param <T> 对象类型
     * @return 返回的对象类型
     */
    public static <T> T newInstance(Class<T> clazz){
        T instance = null;
        try {
            instance = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return instance;
    }

    /**
     * 获取clazz对象的所有公有方法
     * @param clazz clazz对象
     * @return clazz对象的所有公有方法
     */
    public static Method[] getPublicMethod(Class clazz){
        Method[] methods = clazz.getDeclaredMethods();
        LinkedList<Method> methodList = new LinkedList<>();
        for(Method m: methods){
            if(Modifier.isPublic(m.getModifiers())){
                methodList.add(m);
            }
        }
        return methodList.toArray(new Method[0]);
    }


    public static Object invoke(Object obj, Method method, Object... args) throws InvocationTargetException, IllegalAccessException {
        return method.invoke(obj, args);
    }
}
